package com.witmore.skyline.web.service.third.tplink;

import com.witmore.skyline.web.service.CameraCaptureTpService;
import com.witmore.skyline.web.service.third.tplink.dto.TpResultDataDTO;
import com.witmore.skyline.web.service.third.tplink.dto.TpThreadTaskQueueDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@Component
public class TaskWorker {

    @Lazy
    @Autowired
    private CameraCaptureTpService cameraCaptureTpService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    public void run(TpThreadTaskQueueDTO task) {
        threadPoolExecutor.execute(() -> processTask(task));
    }

    private void processTask(TpThreadTaskQueueDTO tpThreadTaskQueueDTO) {
        int retryCount = 0;
        // 设置最大重试次数
        int maxRetries = 10;
        while (retryCount < maxRetries) {
            // 调用第二个接口获取状态
            TpResultDataDTO tpResultDataDTO = cameraCaptureTpService.executeCapturePicTaskStatus(tpThreadTaskQueueDTO.getTaskId());
            int state = tpResultDataDTO.getState();
            switch (state) {
                case 1:
                    // 抓拍进行中，重新放回队列
                    // 为了避免快速重试导致资源浪费，可以适当休眠
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                    retryCount++;
                    break;
                case 10:
                    // 抓拍成功，调用第三个接口获取文件 处理完成后，不需要再放回队列
                    String cameraCaptureFile = cameraCaptureTpService.getCameraCaptureFile(tpThreadTaskQueueDTO);
                    cameraCaptureTpService.saveCaptureRecord(tpThreadTaskQueueDTO, tpResultDataDTO, cameraCaptureFile);
                    return;
                case 11:
                    // 正常结束，丢弃taskId
                    cameraCaptureTpService.saveCaptureRecord(tpThreadTaskQueueDTO, tpResultDataDTO, null);
                    log.warn("Task {} ended normally.", tpThreadTaskQueueDTO.getTaskId());
                    return;
                default:
                    // 处理未知状态
                    cameraCaptureTpService.saveCaptureRecord(tpThreadTaskQueueDTO, tpResultDataDTO, null);
                    log.warn("Unknown state {} for task {}", state, tpThreadTaskQueueDTO.getTaskId());
                    return;
            }
            cameraCaptureTpService.saveCaptureRecord(tpThreadTaskQueueDTO, tpResultDataDTO, null);
        }
        // 超过最大重试次数，可以选择记录日志或采取其他措施
        log.warn("Task {} exceeded max retries.", tpThreadTaskQueueDTO.getTaskId());
    }
}
